package com.flyemu.share.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.blazebit.persistence.PagedList;
import com.flyemu.share.controller.Page;
import com.flyemu.share.controller.PageResults;
import com.flyemu.share.dto.RoleSimpleDto;
import com.flyemu.share.entity.*;
import com.flyemu.share.repository.ProjectRepository;
import com.querydsl.core.BooleanBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @功能描述: 项目管理
 * @创建时间: 2023年08月08日
 * @公司官网: www.fenxi365.com
 * @公司信息: 纷析云（杭州）科技有限公司
 * @公司介绍: 专注于财务相关软件开发, 企业会计自动化解决方案
 */
@Service
@Slf4j
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class ProjectService extends AbsService {

    private final static QProject qProject = QProject.project;

    private final ProjectRepository projectRepository;

    public List<Project> query(Query query) {
        List<Project> list = bqf.selectFrom(qProject)
                .where(query.builder)
                .orderBy(qProject.id.desc()).fetch();
        return list;
    }

    @Transactional
    public Project save(Project project) {
        if (project.getId() != null) {
            //更新
            Project original = projectRepository.getById(project.getId());
            BeanUtil.copyProperties(project, original, CopyOptions.create().ignoreNullValue());
            return projectRepository.save(original);
        }

        return projectRepository.save(project);
    }


    @Transactional
    public void delete(Integer projectId, Integer merchantId) {
        jqf.delete(qProject)
                .where(qProject.id.eq(projectId).and(qProject.merchantId.eq(merchantId)))
                .execute();
    }

    public static class Query {
        public final BooleanBuilder builder = new BooleanBuilder();

        public void setMerchantId(Integer merchantId) {
            if (merchantId != null) {
                builder.and(qProject.merchantId.eq(merchantId));
            }
        }
    }
}
